package com.xuan.yupao.service.impl;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuan.yupao.common.ErrorCode;
import com.xuan.yupao.exception.BusinessException;
import com.xuan.yupao.model.domain.Message;
import com.xuan.yupao.model.domain.PrivateChatSession;
import com.xuan.yupao.model.domain.TeamUser;
import com.xuan.yupao.model.domain.User;
import com.xuan.yupao.model.domain.vo.FromUser;
import com.xuan.yupao.model.domain.vo.MessageVo;
import com.xuan.yupao.model.domain.vo.PrivateMessageVo;
import com.xuan.yupao.service.*;
import com.xuan.yupao.mapper.MessageMapper;
import com.xuan.yupao.utils.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.stream.Collectors;

/**
 * @author 清凉茶
 * @description 针对表【message(消息表)】的数据库操作Service实现
 * @createDate 2024-07-10 13:20:31
 */
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message>
        implements MessageService {

    @Resource
    private PrivateChatSessionService chatSessionService;

    @Resource
    private UserService userService;

    @Resource
    private TeamUserService teamUserService;

    @Override
    public Long getNoRereadMessageNum(Long receiveId) {
        QueryWrapper<Message> messageQueryWrapper = new QueryWrapper<>();
        messageQueryWrapper.eq("receive_id", receiveId);
        messageQueryWrapper.eq("is_read", 0);
        return this.count(messageQueryWrapper);
    }

    @Override
    public List<PrivateMessageVo> getPrivateChatList(Long receiveId) {
        // 1. 查询当前用户存在的私聊会话(有聊天信息)
        QueryWrapper<PrivateChatSession> chatSessionQueryWrapper = new QueryWrapper<>();
        chatSessionQueryWrapper.eq("user_id", receiveId).or().eq("another_user_id", receiveId);
        List<PrivateChatSession> chatSessionList = chatSessionService.list(chatSessionQueryWrapper);
        if (CollectionUtils.isEmpty(chatSessionList)) {
            return new ArrayList<>();
        }


        // 2. 根据每个会话 id 查询最后一条聊天记录
        List<PrivateMessageVo> messageVoList = new ArrayList<>();
        for (PrivateChatSession privateChatSession : chatSessionList) {
            PrivateMessageVo privateMessageVo = new PrivateMessageVo();
            // 1) 查询最后一条消息
            QueryWrapper<Message> messageQueryWrapper = new QueryWrapper<>();
            Long sessionId = privateChatSession.getId();
            messageQueryWrapper.eq("session_id", sessionId);
            messageQueryWrapper.orderByDesc("create_time");
            Message message = this.page(new Page<Message>(1, 1), messageQueryWrapper).getRecords().get(0);
            privateMessageVo.setLastMessage(message.getContent());
            String date = DateUtils.getDateTime(new Date());
            privateMessageVo.setPostTime(date);
            // 2) 查询未读信息数
            messageQueryWrapper = new QueryWrapper<>();
            messageQueryWrapper.eq("session_id", sessionId);
            messageQueryWrapper.eq("receive_id", receiveId);
            messageQueryWrapper.eq("is_read", 0);
            long count = this.count(messageQueryWrapper);
            privateMessageVo.setUnreadNum(count);
            // 3) 查询聊天用户的信息
            Long queryUserId = null;
            Long userId = privateChatSession.getUserId();
            Long anotherUserId = privateChatSession.getAnotherUserId();
            if (Objects.equals(userId, receiveId)) {
                queryUserId = anotherUserId;
            } else {
                queryUserId = userId;
            }
            User user = userService.getById(queryUserId);
            privateMessageVo.setId(queryUserId);
            privateMessageVo.setUsername(user.getUsername());
            privateMessageVo.setAvatarUrl(user.getAvatarUrl());

            messageVoList.add(privateMessageVo);
        }
        return messageVoList;
    }

    @Override
    public List<MessageVo> getPrivateChatHistory(Long toId, Long loginUserId) {
        // 1. 查看是否存在聊天会话
        QueryWrapper<PrivateChatSession> chatSessionQueryWrapper = new QueryWrapper<>();
        chatSessionQueryWrapper.and(wrapper -> wrapper.eq("user_id", toId).eq("another_user_id", loginUserId))
                .or(wrapper -> wrapper.eq("user_id", loginUserId).eq("another_user_id", toId));
        PrivateChatSession chatSession = chatSessionService.getOne(chatSessionQueryWrapper);
        if (chatSession == null) {
            return new ArrayList<>();
        }

        // 2. 根据 sessionId 查询聊天记录
        Long sessionId = chatSession.getId();
        QueryWrapper<Message> messageQueryWrapper = new QueryWrapper<>();
        messageQueryWrapper.eq("session_id", sessionId);
        messageQueryWrapper.orderByAsc("create_time");
        List<Message> messageList = this.list(messageQueryWrapper);
        User user1 = userService.getById(toId);
        User user2 = userService.getById(loginUserId);

        return messageList.stream().map(message -> {
            MessageVo messageVo = new MessageVo();
            FromUser fromUser = new FromUser();
            if (Objects.equals(message.getSendId(), toId)) {
                BeanUtils.copyProperties(user1, fromUser);
            } else {
                BeanUtils.copyProperties(user2, fromUser);
            }
            messageVo.setFromUser(fromUser);
            messageVo.setText(message.getContent());
            String date = DateUtils.getDateTime(new Date());
            messageVo.setCreateTime(date);
            return messageVo;
        }).collect(Collectors.toList());
    }

    @Override
    public List<MessageVo> getTeamChatHistory(Long teamId, Long loginUserId) {
        // 1. 查看用户是否在该队伍中
        QueryWrapper<TeamUser> teamUserQueryWrapper = new QueryWrapper<>();
        teamUserQueryWrapper.eq("team_id", teamId).eq("user_id", loginUserId);
        long count = teamUserService.count(teamUserQueryWrapper);
        if (count < 1) {
            throw new BusinessException(ErrorCode.NOT_AUTH, "您当前不在队伍中");
        }

        // 2. 获取队伍中的所有用户信息
        teamUserQueryWrapper = new QueryWrapper<>();
        teamUserQueryWrapper.eq("team_id", teamId);
        List<Long> userIdList = teamUserService.list(teamUserQueryWrapper).stream().map(TeamUser::getUserId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(userIdList)) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "队伍不存在");
        }
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.in("id", userIdList);
        //  userId - user
        Map<Long, List<User>> userMap = userService.list(userQueryWrapper).stream().collect(Collectors.groupingBy(User::getId));

        // 3. 获取当前队伍的所有消息
        QueryWrapper<Message> messageQueryWrapper = new QueryWrapper<>();
        messageQueryWrapper.eq("team_id", teamId);
        List<Message> messageList = this.list(messageQueryWrapper);
        return messageList.stream().map(message -> {
            MessageVo messageVo = new MessageVo();
            User user = userMap.get(message.getSendId()).get(0);
            FromUser fromUser = new FromUser();
            BeanUtils.copyProperties(user, fromUser);
            messageVo.setFromUser(fromUser);
            messageVo.setText(message.getContent());
            String date = DateUtils.getDateTime(new Date());
            messageVo.setCreateTime(date);
            return messageVo;
        }).collect(Collectors.toList());
    }

    @Override
    public List<MessageVo> getHallChatHistory(Long userId) {
        // 1. 获取大厅的所有聊天记录
        QueryWrapper<Message> messageQueryWrapper = new QueryWrapper<>();
        messageQueryWrapper.eq("chat_type", 3);
        List<Message> messageList = this.list(messageQueryWrapper);

        // 2. 查询聊天记录中所有发送者的信息(先去重,再查询)
        List<Long> userIdList = messageList.stream().map(Message::getSendId).distinct().collect(Collectors.toList());
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.in("id", userIdList);
        // userId - User
        Map<Long, List<User>> userMap = userService.list(userQueryWrapper).stream().collect(Collectors.groupingBy(User::getId));

        // 3. 返回所有历史消息(脱敏)
        return messageList.stream().map(message -> {
            MessageVo messageVo = new MessageVo();
            FromUser fromUser = new FromUser();
            BeanUtils.copyProperties(userMap.get(message.getSendId()).get(0), fromUser);
            messageVo.setFromUser(fromUser);
            messageVo.setText(message.getContent());
            messageVo.setCreateTime(DateUtils.getDateTime(message.getCreateTime()));
            return messageVo;
        }).collect(Collectors.toList());
    }

    @Override
    public boolean confirmUnreadMessage(Long remoteId, Long loginUserId) {
        // 1. 获取两个用户间的 会话id
        QueryWrapper<PrivateChatSession> chatSessionQueryWrapper = new QueryWrapper<>();
        chatSessionQueryWrapper.and(wrapper -> wrapper.eq("user_id", remoteId).eq("another_user_id", loginUserId))
                .or(wrapper -> wrapper.eq("user_id", loginUserId).eq("another_user_id", remoteId));
        PrivateChatSession chatSession = chatSessionService.getOne(chatSessionQueryWrapper);
        if (chatSession == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "不存在聊天会话");
        }

        // 2. 修改数据库数据 is_read字段 为true
        UpdateWrapper<Message> messageUpdateWrapper = new UpdateWrapper<>();
        messageUpdateWrapper.eq("session_id", chatSession.getId());
        messageUpdateWrapper.eq("send_id", remoteId).eq("receive_id", loginUserId);
        messageUpdateWrapper.set("is_read", 1);
        return this.update(messageUpdateWrapper);
    }


}




